<?php

namespace App\Model;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MallGoods extends BaseModel
{
    protected $table = 'mall_goods';
    protected $mallGoodsLabelTable = 'mall_goods_label';
    protected $tableMallGoodsUpgradeConfig = 'mall_goods_upgrade_config';
    protected $connectionGupConfig = 'api';
    protected $primaryKey = 'goods_id';
    public $timestamps = false;
    protected $fillable = ['goods_name','goods_type','small_img','big_img','animate_resource','is_new','is_show','sort','create_timestamp'];
    private $fields = ['goods_id','goods_name','goods_type','small_img','is_show','sort','is_new','animate_resource','big_img','animate_resource_md5','animate_resource_small','animate_resource_big', 'vapc_json_url', 'give_data_id','is_new_mount','text_color','goods_desc','is_buy','from_desc','from_url','url_start_time','url_end_time','label_id','level','mall_goods_class','renew_card_num', 'cool_val', 'debris_num', 'is_upgrade'];


    public function mallGoodsSku(){
        return $this->hasMany(MallGoodsSku::class, 'goods_id', 'goods_id');
    }

    public function mallShoplog(){
        return $this->hasMany(MallShoplog::class,'goods_id','goods_id');
    }

    public function getList(Request $request){
        $limit = $request->input('limit', 10);
        $page = $request->input('page',1);
        $goods_type = $request->input('goods_type',1);
        $gift_id = $request->input('gift_id','');
        $gift_name = $request->input('gift_name','');

        $mall_goods_class = (int)$request->input('mall_goods_class','');// 全部-1
        $level = (int)$request->input('level','');// 全部-1

        $where = [];
        if($gift_id != '') $where[] = ['goods_id', '=', $gift_id];
        if($gift_name != '') $where[] = ['goods_name', 'like', "%{$gift_name}%"];
        if($goods_type) $where[] = ['goods_type', '=', $goods_type];

        if ($mall_goods_class != -1){
            $where[] = ['mall_goods_class', '=', $mall_goods_class];
        }
        if ($level != -1){
            $where[] = ['level', '=', $level];
        }

        $query = new MallGoods();

        return $query->with('mallGoodsSku:sku_id,goods_id,time_limit,price,default')
            ->orderBy('goods_id','desc')
            ->where($where)
            ->paginate($limit, $this->fields,'page',$page);
    }

    public function getGoodsByType($type){
        return MallGoods::where('goods_type',$type)->get(['goods_id','goods_name']);
    }
    public function getUnGoodsByType($type){
        return MallGoods::where('goods_type',$type)->where('extra_type',1)->get(['goods_id','goods_name']);
    }

    public function getGoodByGoodId(int $good_id){
        return self::with(['mallGoodsSku'])->find($good_id);
    }

    public function getGoodByGoodName(string $name){
        return self::where('goods_name','LIKE',"{$name}%")->with(['mallGoodsSku'])->get();
    }

    /**
     * 商品周期统计
     * @return mixed
     */
    public function statisticsGoodsCycle($input = []){
        $page = $input['page'] ?? 1;
        $limit = $input['limit'] ?? 10;
        $page = ($page - 1) * $limit;
        $goods_type = $input['goods_type'] ?? 0;
        $where = '';
        if($goods_type){
            $where = " AND a.goods_type={$goods_type}";
        }

        $monday = date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600));
        $sunday = date('Y-m-d', (time() + (7 - (date('w') == 0 ? 7 : date('w'))) * 24 * 3600));
        $currentMonthFirst = date('Y-m-01');
        $currentMonthEnd = date('Y-m-d', strtotime("{$currentMonthFirst} +1 month -1 day"));

        // 总数
        $total = DB::connection('api')->selectOne("SELECT
    COUNT(*) AS total
FROM
    zb_mall_goods AS a
LEFT JOIN
    zb_mall_shoplog AS c
ON
    a.goods_id=c.goods_id
WHERE
    1=1 {$where}
GROUP BY a.goods_id");

        $sql = "SELECT a.goods_id,a.goods_name,a.goods_type,
SUM(CASE WHEN FROM_UNIXTIME(c.create_timestamp,'%Y-%m-%d') = curdate() THEN c.price else 0 END) as dsum,
SUM(CASE WHEN FROM_UNIXTIME(c.create_timestamp,'%Y-%m-%d') = DATE_SUB(curdate(),INTERVAL 1 DAY) THEN c.price else 0 END) as ysum,
SUM(CASE WHEN FROM_UNIXTIME(c.create_timestamp,'%Y-%m-%d')>='{$monday}' AND FROM_UNIXTIME(c.create_timestamp,'%Y-%m-%d') <='{$sunday}' THEN c.price else 0 END) as wsum,
SUM(CASE WHEN FROM_UNIXTIME(c.create_timestamp,'%Y-%m-%d') >= '{$currentMonthFirst}' AND FROM_UNIXTIME(c.create_timestamp,'%Y-%m-%d')<='{$currentMonthEnd}'  THEN c.price else 0 END) as msum
from zb_mall_goods as a LEFT JOIN zb_mall_shoplog as c
ON a.goods_id = c.goods_id
WHERE 1=1 {$where}
GROUP BY a.goods_id LIMIT {$page},{$limit}";
        DB::connection()->disableQueryLog();
        $data = DB::connection('api')->select($sql);

        $users = DB::connection('api')->select("SELECT COUNT( DISTINCT user_id) as usum,goods_id FROM zb_mall_user_goods GROUP BY goods_id");
        $users = array_column($users,'usum','goods_id');
        $list = collect($data)->map(function($item) use($users){
            $item->usum = $users[$item->goods_id] ?? 0;
            return $item;
        })->sortByDesc('usum');
        return ['data' => $list, 'total' => $total->total];
    }

//    protected $tableMallGoodsUpgradeConfig = 'mall_goods_upgrade_config';

    function getGupConfigList($goods_id)
    {
        $list = DB::connection($this->connectionGupConfig)->table($this -> tableMallGoodsUpgradeConfig)->where('goods_id', $goods_id)->get();
        $list = $this -> objToArray($list);
        return $list;
    }

    //添加
    public function createGoods($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/mall/create', $data, 'json', 'POST');
    }

    //更新
    public function updateGoods($data)
    {
        $url = getKkaudioApiUrl();
        return curl_request($url . '/inner/mall/update', $data, 'json', 'POST');
    }

    //删除
    public function removeGoods($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/mall/remove', $data, 'urlencoded', 'GET');
    }


    //添加
    public function createData($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/mall/sku_create', $data, 'json', 'POST');
    }

    //更新
    public function updateData($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/mall/sku_update', $data, 'json', 'POST');
    }

    //删除
    public function removeData($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/mall/sku_remove', $data, 'urlencoded', 'GET');
    }

    //添加商品标签
    public function labelCreate($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/mall/label/create', $data, 'json', 'POST');
    }

    //获取所有商品标签
    public function getLabel()
    {
        $labelList = DB::connection('api')->table($this->mallGoodsLabelTable)->get();
        return $this->objToArray($labelList);
    }

    //删除某个商品标签
    public function delLabel($id)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/mall/label/del', ['id' => $id], 'json', 'POST');
    }

    //编辑某个商品标签
    public function labelEdit($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/mall/label/edit', $data, 'json', 'POST');
    }
    public function getGoodsBygoodIds($goods_ids){
        return DB::connection('api')->table('mall_goods')->whereIn('goods_id',$goods_ids)->get(['goods_id','goods_name','goods_type','small_img'])->toArray();
    }

    // 商品等级
    public function getGoodsLevelList($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/mall/goods_level/list', $data, 'urlencoded', 'GET');
    }

}
